package cn.jdemo.io.writer;


import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @see Writer 抽象基类
 * @see BufferedWriter
 *
 * 构造方法
 * @see BufferedWriter#BufferedWriter(Writer) 默认缓存大小8192
 * @see BufferedWriter#BufferedWriter(Writer, int sz) 设置写入输出流前的缓存大小
 *
 * 成员变量
 * @see BufferedWriter#writeBuffer Writer基类的字符缓冲区(大小1024),若wirte(str)的字符长度大于1024，则其设置为字符长度，否则设置为1024
 * @see BufferedWriter#cb BufferedWriter的字符缓冲区,若cb大小 > writeBuffer,则writerBuffer数据copy到cb,否则刷新cb到底层输出流并把writeBuffer也写到底层输出流
 * @see BufferedWriter#nChars cb实际大小
 *
 * @date 2020/12/23
 */
public class Demo01_BufferedWriter {
    public static void main(String[] args) {
        // test01();
        // test02();
        test03();
    }

    /**
     * <code>反例</code>
     * @see BufferedWriter#cb BufferedWriter的字符缓冲区大小设置为2
     * @see BufferedWriter#write(String) 使用当前方法时，若字符长度小于1024，则Writer#writeBuffer缓存区大小为1024
     * 发射刷新也不好使
     */
    public static void test01() {
        BufferedWriter bufferedWriter = null;
        try {
            FileWriter fileWriter = new FileWriter("D:\\test.txt");
            bufferedWriter = new BufferedWriter(fileWriter,2);
            bufferedWriter.write("abc+中文字符串123中文汉字");

            Class<? extends BufferedWriter> aClass = bufferedWriter.getClass();
            Method flushBuffer = aClass.getDeclaredMethod("flushBuffer");
            flushBuffer.setAccessible(true);
            flushBuffer.invoke(bufferedWriter, null);

            Field out = aClass.getDeclaredField("out");
            out.setAccessible(true);
            out.set(bufferedWriter,null);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    public static void test02() {
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter("D:\\test.txt"),2);
            bufferedWriter.write("abc+中文字符串123");
            // bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedWriter.close();// 关闭流资源前，会刷新缓存数据到流中
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * jdk8新特性:try()括号中声明流，则自动释放资源
     */
    public static void test03() {
        try (BufferedWriter bufferedWriter =
                     new BufferedWriter(new FileWriter("D:\\test.txt"),2)){
            bufferedWriter.write("abc+中文字符串123");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
